package com.cloudspace.jindun.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.interphone.ChangeChannelActivity;
import com.cloudspace.jindun.activity.interphone.MyChannelActivity;
import com.cloudspace.jindun.adapter.CurrentChannelDetailAdapter;
import com.cloudspace.jindun.callback.AudioSendCallback;
import com.cloudspace.jindun.callback.PlayFinishCallback;
import com.cloudspace.jindun.callback.StartRecordingCallback;
import com.cloudspace.jindun.config.Configs;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.ext.aq.AQUtility;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.manager.MessageNumberManager;
import com.cloudspace.jindun.model.ChannelMemberStatus;
import com.cloudspace.jindun.model.ChannelMemberStatusResult;
import com.cloudspace.jindun.model.CommonResult;
import com.cloudspace.jindun.model.DefaultChannelResult;
import com.cloudspace.jindun.model.MicResult;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.AppPreferences;
import com.cloudspace.jindun.utils.AudioManager;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.utils.VibratorUtils;
import com.cloudspace.jindun.websocket.WebSocketManager;
import com.cloudspace.jindun.websocket.WebSocketMessageController;

import org.apache.http.HttpStatus;

import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.List;

import de.tavendo.autobahn.WebSocket;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.VoiceMessage;

import static com.cloudspace.jindun.fragment.InterPhoneFragment.WebSocketHandler.MSG_GREEN_ANIMATE;
import static com.cloudspace.jindun.fragment.InterPhoneFragment.WebSocketHandler.MSG_RED_ANIMATE;

/**
 * Created by zengxianhua on 16/12/19.
 */

public class InterPhoneFragment extends BaseFragment implements View.OnClickListener {
    public static final String TAG = InterPhoneFragment.class.getSimpleName();

    private static final String ARG_SECTION_NUMBER = "section_number";

    private View changeChannel;
    private View myChannel;

    private View mSpeakView;
    private ImageView mAnimationImg;

    private String mCurrentChannelId = "";

    private ImageView beSilentSwitch;
    private boolean isSilent = false;

    private boolean isMeSpeak;
    private boolean isUrgency; //紧急

    private final int MIC_CANCEL = 0;
    private final int MIC_WAIT = 1;
    private final int MIC_FINISH = 2;
    private final int MIC_SPEAK = 3;

    private final int MIC_LEAVE = 4;
    private final int MIC_IN = 5;

    private TextView statusText;

    private ListView mCurrentChannelListView;
    private CurrentChannelDetailAdapter mCurrentChannelAdapter;

    private View urgencyLy;
    private TextView urgencyTv;

    private boolean longPressed = false;
    // websocket
    private WebSocketHandler webSocketHandler = new WebSocketHandler(this);
    private WebSocketLister mWsListener = new WebSocketLister(this);

    final Handler handler = new Handler();
    Runnable mLongPressed = new Runnable() {
        public void run() {
            longPressed = true;
            requestSpeak();
        }
    };

    private View.OnTouchListener speakTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();

            if (!UserSessionManager.yyCanUse()){
                ToastMaker.showToastShort(R.string.yy_not_available);
                return true;
            }

            if (action == MotionEvent.ACTION_DOWN){
                handler.postDelayed(mLongPressed, 500);
            }else if (action == MotionEvent.ACTION_UP){
                handler.removeCallbacks(mLongPressed);
                if (longPressed){
                    upOperation();
                    longPressed = false;
                }
            }

            return true;
        }
    };

    private void upOperation() {
        if (isMeSpeak){
            //如果当前正在发言
            stopSpeak();
        }else{
            //告诉服务器放弃发言
            cancelSpeak();
        }
    }

    private PlayFinishCallback playFinishCallback = new PlayFinishCallback() {
        @Override
        public void onComplete() {
            if (mCurrentChannelAdapter != null){
                mCurrentChannelAdapter.setPlayState(false);
            }

            //播放完发finishmic消息
            if (isMeSpeak){
                finishMic();
            }

            if (isMeSend){
                enableSpeakView(true);
                isMeSend = false;
            }
        }
    };

    private boolean isMeSend = false;

    private AudioSendCallback audioCallback = new AudioSendCallback() {
        @Override
        public void success(Message message) {
            boolean isUrgencyMessage = (message != null && message.getContent() != null
                    && ("isUrgency").equals(((VoiceMessage)message.getContent()).getExtra()));

            final String senderId = message.getSenderUserId();
            APPLog.zxhLog(TAG + " message sender id:" + senderId);

            isMeSend = TextUtils.equals(UserSessionManager.getInstance().getUserId(), senderId);


            //播放语音
            if (isUrgencyMessage || !UserSessionManager.getInstance().isSilent()){
                //非静默状态
                AudioManager.getInstance().playVoiceMessage((VoiceMessage) message.getContent(),
                        playFinishCallback, isMeSend);
            }

            //更新status
            AQUtility.post(new Runnable() {
                @Override
                public void run() {
                    updateChannelStatus(senderId);

                    if (isMeSend){
                        enableSpeakView(false);
                    }else{
                        enableSpeakView(true);
                    }

                }
            });

        }

        @Override
        public void fail() {

        }
    };
    private StartRecordingCallback startRecordingCallback = new StartRecordingCallback() {
        @Override
        public void onSuccess() {

        }

        @Override
        public void onFail() {
            ToastMaker.showToastShort(JindunApp.getInstance().getString(R.string.check_audio));
            stopSpeak();

            AQUtility.post(new Runnable() {
                @Override
                public void run() {
                    enableSpeakView(false);
                }
            });
        }
    };

    private void updateChannelStatus(String senderId) {
        if (TextUtils.isEmpty(senderId) ||
                ObjUtil.isEmpty(mCurrentChannelAdapter.getData())){
            return;
        }

        List<ChannelMemberStatus> members = mCurrentChannelAdapter.getData();
        int index = -1;

        for (int i = 0; i < members.size(); ++i){
            if (TextUtils.equals(senderId, members.get(i).id)){
                index = i;
                break;
            }
        }

        if (index > 0 && index < members.size()){
            //将这个元素挪到第一个去
            Collections.swap(members, 0, index);
        }

        mCurrentChannelAdapter.setPlayState(true);
        setChannelMemberData(members);
    }

    private void cancelSpeak() {
        stopWaitAnimation();
        API.getInstance().getChannelApi().cancelMic(TAG, mCurrentChannelId, new ApiCallback<MicResult>() {
            @Override
            public void handleResult(MicResult result, VolleyError error) {
            }
        }.toastActionError());

        updateTipStatusText(MIC_CANCEL);
    }

    private boolean waitStatus = false;

    private void updateTipStatusText(final int mic_status) {
        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                if (mic_status == MIC_CANCEL){
                    //用户取消
                    waitStatus = false;
                    statusText.setVisibility(View.GONE);
                }else if(mic_status == MIC_WAIT){
                    //排队
                    statusText.setVisibility(View.VISIBLE);
                    waitStatus = true;
                    statusText.setText(getResources().getString(R.string.wait_normal));
                }else if (mic_status == MIC_FINISH){
                    //用户结束
                    statusText.setVisibility(View.GONE);
                }else if (mic_status == MIC_SPEAK){
                    statusText.setVisibility(View.VISIBLE);
                    statusText.setText(getResources().getString(R.string.speak_now));
                }
            }
        });
    }

    public void setConnected(boolean connected) {
        this.connected = connected;
    }

    static class WebSocketLister implements WebSocketManager.IWebSocketListener {

        WeakReference<InterPhoneFragment> ref;

        public WebSocketLister(InterPhoneFragment fragment) {
            ref = new WeakReference<>(fragment);
        }

        boolean isFinish() {
            return ref == null || ref.get() == null || ref.get().isAdded();
        }

        public void open() {
            APPLog.zxhLog(TAG + "ws open callback");
            ref.get().setConnected(true);
            ref.get().startPing();
        }

        public void error(int errorCode, String errorMessage) {
            APPLog.zxhLog("connect web socket errorCode : " + errorCode + " , errorMessage : " + errorMessage);
            ref.get().setConnected(false);
            if (errorCode == WebSocket.ConnectionHandler.CLOSE_NORMAL) {
                return;
            }
            // 关闭socket
            WebSocketMessageController.getInstance().close(true);
        }
    }

    private void startPing() {
        WebSocketMessageController.getInstance().startPing(15);
    }

    static class WebSocketHandler extends WebSocketMessageController.WSHandler{
        private WeakReference<InterPhoneFragment> ref;

        public static final int MSG_GREEN_ANIMATE = 100;
        public static final int MSG_RED_ANIMATE = 101;

        public WebSocketHandler(InterPhoneFragment fragment){
            ref = new WeakReference<InterPhoneFragment>(fragment);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            if (ref == null || ref.get() == null){
                return;
            }

            InterPhoneFragment fragment = ref.get();
            switch (msg.what){
                case COMMAND_TYPE_CHANGEMIC:
                    fragment.onReceiveChangeMicMessage((WebSocketMessageController.ChangeMicMessage) msg.obj);
                    break;

                case COMMAND_TYPE_MICINFO:
                    fragment.onReceiveMicInfoMessage((WebSocketMessageController.MicInfoMessage) msg.obj);
                    break;

                case MSG_GREEN_ANIMATE:
                    fragment.doGreenAnimation();
                    break;

                case MSG_RED_ANIMATE:
                    fragment.doRedAnimation();
                    break;

                case COMMAND_TYPE_MIC_USER_IN:
                    fragment.onReceiveUserInMessage((WebSocketMessageController.MicUserInMessage) msg.obj);
                    break;

                case COMMAND_TYPE_MIC_USER_OUT:
                    fragment.onReceiveUserOutMessage((WebSocketMessageController.MicUserOutMessage) msg.obj);
                    break;

                default:
                    break;
            }
        }
    }

    private void onReceiveUserOutMessage(WebSocketMessageController.MicUserOutMessage msg) {
        if (ObjUtil.isEmpty(msg)){
            return;
        }

        APPLog.zxhLog(TAG + "onReceiveUserOutMessage :" + msg.member.name);

        delteMember(msg.member);
    }

    private void delteMember(ChannelMemberStatus member) {
        if (ObjUtil.isEmpty(member) ||
                ObjUtil.isEmpty(mCurrentChannelAdapter)
                || ObjUtil.isEmpty(mCurrentChannelAdapter.getData())){
            return;
        }

        final List<ChannelMemberStatus> datas = mCurrentChannelAdapter.getData();

        int index = -1;

        for (int i = 0; i < datas.size(); ++i){
            if (TextUtils.equals(member.id, datas.get(i).id)){
                index = i;
                break;
            }
        }

        if (index != -1){
            APPLog.zxhLog(TAG + "delteMember user find");
            datas.remove(index);
        }

        setChannelMemberData(datas);
    }

    private void addMember(ChannelMemberStatus member) {
        if (ObjUtil.isEmpty(member) ||
                ObjUtil.isEmpty(mCurrentChannelAdapter)
               ){
            return;
        }

        final List<ChannelMemberStatus> datas = mCurrentChannelAdapter.getData();

        int index = -1;

        for (int i = 0; i < datas.size(); ++i){
            if (TextUtils.equals(member.id, datas.get(i).id)){
                index = i;
                break;
            }
        }

        if (index != -1){
            APPLog.zxhLog(TAG + "add member");
            datas.add(member);

            setChannelMemberData(datas);
        }
    }

    private void setChannelMemberData(final List<ChannelMemberStatus> datas) {
        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                mCurrentChannelAdapter.setDatas(datas);
            }
        });
    }

    private void onReceiveUserInMessage(WebSocketMessageController.MicUserInMessage msg) {
        if (ObjUtil.isEmpty(msg)){
            return;
        }

        APPLog.zxhLog(TAG + "onReceiveUserInMessage :" + msg.member.name);
        addMember(msg.member);
    }

    private void checkVoicePermission(){
        try{
            AudioManager.getInstance().checkRecordPermission();
        }catch (Exception e){

        }
    }

    private void doRedAnimation() {
        currentDrawableIndex = (currentDrawableIndex + 1)%animationIndex.length;
        mAnimationImg.setImageResource(redDrawables[animationIndex[currentDrawableIndex]]);

        android.os.Message msg = webSocketHandler.obtainMessage(MSG_RED_ANIMATE);
        webSocketHandler.sendMessageDelayed(msg, ANIMATION_DURATION);
    }

    private void doGreenAnimation() {
        currentDrawableIndex = (currentDrawableIndex + 1)%animationIndex.length;
        mAnimationImg.setImageResource(greenDrawables[animationIndex[currentDrawableIndex]]);

        android.os.Message msg = webSocketHandler.obtainMessage(MSG_GREEN_ANIMATE);
        webSocketHandler.sendMessageDelayed(msg, ANIMATION_DURATION);
    }

    private void onReceiveChangeMicMessage(WebSocketMessageController.ChangeMicMessage model) {
        APPLog.zxhLog(TAG + " ChangeMicMessage:" + model.userId);
        if (model.userId.equals(UserSessionManager.getInstance().getUserId())){
            //清除等待动画
            stopWaitAnimation();

            //轮到自己发语音
            startSpeak();
        }
    }

    private void onReceiveMicInfoMessage(WebSocketMessageController.MicInfoMessage model) {
        APPLog.zxhLog(TAG + " MicInfoMessage:" + model.userId + " " + model.type);
        updateMicInfoStatus(model);
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_duijiang, container, false);
        return rootView;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        changeChannel = view.findViewById(R.id.change_my_ly);
        myChannel = view.findViewById(R.id.my_channel_ry);

        mCurrentChannelListView = (ListView) view.findViewById(R.id.duijiang_lv_member);
        mCurrentChannelAdapter = new CurrentChannelDetailAdapter(getActivity());
        mCurrentChannelListView.setAdapter(mCurrentChannelAdapter);

        beSilentSwitch = (ImageView) view.findViewById(R.id.inter_switch);
        beSilentSwitch.setOnClickListener(this);
        changeChannel.setOnClickListener(this);
        myChannel.setOnClickListener(this);

        mSpeakView = view.findViewById(R.id.speakRl);
        mSpeakView.setOnTouchListener(speakTouchListener);

        mAnimationImg = (ImageView) view.findViewById(R.id.animation_bg_img);
        mAnimationImg.setVisibility(View.GONE);
        statusText = (TextView) view.findViewById(R.id.status_text);
        statusText.setVisibility(View.GONE);

        urgencyLy = view.findViewById(R.id.urgencyLy);
        urgencyTv = (TextView) view.findViewById(R.id.duijiang_tv_emergencyCall);
        urgencyLy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUrgencyStatus(true);
            }
        });

        initReceiveListener();
        setCurrentChannelId(
                AppPreferences.getString(Constants.USER_LAST_ACTIVE_CHANNEL
                        + UserSessionManager.getInstance().getUserId(), ""));
    }

    private void isUrgencyStatus(final boolean status) {
        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                isUrgency = status;

                urgencyTv.setText(isUrgency ?
                        getResources().getText(R.string.emergency_calling) :
                        getResources().getText(R.string.emergency_call)
                );
            }
        });


    }

    private void setCurrentChannelId(String channelId) {
        APPLog.zxhLog(TAG + " setCurrentChannelId:" + channelId);
        mCurrentChannelId = channelId;

        if (!TextUtils.isEmpty(channelId)){
            //频道号发生变化，得重连
            String ws = getWSUrl();
            connectWebSocket(ws);
        }
    }

    private String getWSUrl() {
        return String.format("ws://%s/channelId=%s/userId=%s", Configs.WS_IP, mCurrentChannelId,
                UserSessionManager.getInstance().getUserId());
    }

    private void initReceiveListener() {
        RongIM.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int i) {
                APPLog.zxhLog(TAG + " onReceived:" + message + " sender id:" + message.getSenderUserId());
                //接收到语音消息

                if (!message.getTargetId().equals(mCurrentChannelId)){
                    //不属于当前
                    MessageNumberManager.getInstance().addMessageUnread(message.getTargetId());
                    return false;
                }

                if (UserSessionManager.isVibrateOn()){
                    VibratorUtils.vibrate();
                }
                if (message.getConversationType().equals(Conversation.ConversationType.GROUP)
                        && (message.getContent() != null && (message.getContent() instanceof VoiceMessage))
                        ) {
                    audioCallback.success(message);
                }
                return false;
            }
        });
    }

    @Override
    public void onFragmentCreated(Bundle savedInstanceState) {
        checkVoicePermission();
    }

    @Override
    public void updateContent() {

    }

    @Override
    public void onResume() {
        super.onResume();

        loadChannelStatus();
    }

    private void loadChannelStatus() {
        if (TextUtils.isEmpty(mCurrentChannelId)){
            getDefaultChannel();
        }else{
            getChannelMemberStatus();
        }

    }

    private void getDefaultChannel() {
        API.getInstance().getChannelApi().getDefaultChannel(TAG, new ApiCallback<DefaultChannelResult>() {
            @Override
            public void handleResult(DefaultChannelResult result, VolleyError error) {
                if (result != null && result.status == HttpStatus.SC_OK){
                    if (!TextUtils.isEmpty(result.data)){
                        mCurrentChannelId = result.data;

                        APPLog.zxhLog(TAG + "default channel id:" + mCurrentChannelId);
                    }
                    getChannelMemberStatus();
                }
            }
        });
    }

    private void getChannelMemberStatus() {
        if (TextUtils.isEmpty(mCurrentChannelId)){
            return;
        }

        APPLog.zxhLog("%s[%s]", TAG, "getChannelMemberStatus");

        API.getInstance().getChannelApi().getCurrentChannelMemberStatus(TAG, mCurrentChannelId,
                new ApiCallback<ChannelMemberStatusResult>() {
                    @Override
                    public void handleResult(ChannelMemberStatusResult result, VolleyError error) {
                        if (result != null && result.status == HttpStatus.SC_OK){
                            setChannelMemberData(result.data);
                            updateSilentStatus(result.data);

                            if (ObjUtil.isEmpty(result.data)){
                                mCurrentChannelId = "";
                            }
                        }else if (error != null){
                            ToastMaker.showToastShort(error.getMessage());
                        }
                    }
                });
    }

    private void updateMicInfoStatus(WebSocketMessageController.MicInfoMessage message) {
        APPLog.zxhLog(TAG + " updateMicInfoStatus");
        loadChannelStatus();
//        if (ObjUtil.isEmpty(message)){
//            return;
//        }
//
//        List<ChannelMemberStatus> members = mCurrentChannelAdapter.getData();
//        int index = -1;
//
//        for (int i = 0; i < members.size(); ++i){
//            if (TextUtils.equals(message.userId, members.get(i).id)){
//                index = i;
//                break;
//            }
//        }
//
//        if (index != 0){
//            //将这个元素挪到第一个去
//            ChannelMemberStatus member = members.get(index);
//            member.status = message.type;
//            member.lastActionTime = message.time;
//        }
//
//        mCurrentChannelAdapter.setPlayState(true);
//        setChannelMemberData(members);
    }

    private void updateSilentStatus(List<ChannelMemberStatus> data) {
        for (ChannelMemberStatus status : data){
            if (status.id.equals(UserSessionManager.getInstance().getUserId())){
                setSilentStatus(Constants.CHANNEL_STATUS_SILENT.equals(status.status));

                enableSpeakView(!isSilent);
            }
        }
    }

    public static InterPhoneFragment newInstance(int sectionNumber){
        InterPhoneFragment fragment = new InterPhoneFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.change_my_ly:
                changeChannel();
                break;

            case R.id.my_channel_ry:
                myChannel();
                break;

            case R.id.inter_switch:
                silentSwitch();
                break;

            default:
                break;
        }
    }

    private boolean isChannelValid(){
        return !TextUtils.isEmpty(mCurrentChannelId);
    }

    private void requestSpeak() {
        if (!isChannelValid()){
            ToastMaker.showToastLong(JindunApp.getInstance().getText(R.string.channel_invalid));
            return;
        }

        API.getInstance().getChannelApi().controlMic(TAG, mCurrentChannelId, new ApiCallback<MicResult>() {
            @Override
            public void handleResult(MicResult result, VolleyError error) {
                if (result != null && result.status == HttpStatus.SC_OK && result.data != null){
                    if (result.data.equals(UserSessionManager.getInstance().getUserId())){
                        //抢到发言权，开始发言
                        startSpeak();
                    }else{
                        //处于等待状态
                        updateTipStatusText(MIC_WAIT);
                        loadWaitAnimation();
                    }

                }else if (error != null){
                    ToastMaker.showToastShort(getResources().getString(R.string.request_error) + error.getMessage());
                }
            }
        });
    }

    private void setSilentStatus(boolean silent){
        APPLog.zxhLog(TAG + " 是否静默:" + silent);
        isSilent = silent;
        beSilentSwitch.setImageResource(isSilent ? R.drawable.inter_shut : R.drawable.off);
        UserSessionManager.getInstance().setSilent(silent);
    }

    private void silentSwitch() {
        String userStatus = (isSilent) ? Constants.CHANNEL_STATUS_ONLINE : Constants.CHANNEL_STATUS_SILENT;

        API.getInstance().getChannelApi().modifyChannel(TAG, mCurrentChannelId, UserSessionManager.getInstance().getUserId()
                , userStatus, new ApiCallback<CommonResult>() {
                    @Override
                    public void handleResult(CommonResult result, VolleyError error) {
                        if (result != null && result.status == HttpStatus.SC_OK){
                            ToastMaker.showToastShort(getResources().getString(R.string.switch_success));
                            setSilentStatus(!isSilent);

                            enableSpeakView(!isSilent);
                            loadChannelStatus();
                        }else{
                            ToastMaker.showToastShort(getResources().getString(R.string.switch_fail));
                        }
                    }
                });

    }

    private void enableSpeakView(boolean able) {
        mSpeakView.setBackgroundResource(able ? R.drawable.lan : R.drawable.hui);
        mSpeakView.setEnabled(able);
    }

    private void myChannel() {
        //我的频道
        MyChannelActivity.showActivity(getActivity());
    }

    private void changeChannel() {
        //切换频道
        ChangeChannelActivity.showActivityForResult(this, mCurrentChannelId);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ChangeChannelActivity.CHANNEL_CHANGE_ID && data != null){
            String channelId = data.getStringExtra("channelid");

            if (!TextUtils.isEmpty(channelId)){
                setCurrentChannelId(channelId);
                loadChannelStatus();
                AppPreferences.putString(Constants.USER_LAST_ACTIVE_CHANNEL+
                                UserSessionManager.getInstance().getUserId(),
                        mCurrentChannelId);
            }
        }
    }

    public void startSpeak(){
        APPLog.zxhLog(TAG + " startSpeak");

        if (isMeSpeak){
            return;
        }

        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                loadSpeakAnimation();

                updateTipStatusText(MIC_SPEAK);
                boolean tipAppear = JindunApp.getInstance().pre.getBoolean("record_tip", false);
                if (!tipAppear){
                    JindunApp.getInstance().pre.edit().putBoolean("record_tip", true).commit();
                    ToastMaker.showToastShort(getResources().getString(R.string.begin_speak));
                }
                isMeSpeak = true;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                AudioManager.getInstance().startRecord(startRecordingCallback);
            }
        }).start();
    }

    private boolean connected;

    public void connectWebSocket(final String ws) {
        WebSocketMessageController.getInstance().setWSHandler(webSocketHandler);
        WebSocketMessageController.getInstance().setListener(mWsListener);

        WebSocketMessageController.getInstance().connect(ws);
    }

    private int[] greenDrawables = new int[] {
            R.drawable.lv_01,
            R.drawable.lv_02,
            R.drawable.lv_03,
            R.drawable.lv_04
    };

    private int[] redDrawables = new int[] {
            R.drawable.ho_01,
            R.drawable.ho_02,
            R.drawable.ho_03,
            R.drawable.ho_04
    };

    private final int ANIMATION_RED = 0;
    private final int ANIMATION_GREEN = 1;

    private int[] animationIndex = new int[]{
            0,1,2,3,2,1,
    };

    private int currentDrawableIndex = 0;

    private int ANIMATION_DURATION = 300;

    public void loadSpeakAnimation(){
        android.os.Message msg = webSocketHandler.obtainMessage(MSG_GREEN_ANIMATE);
        webSocketHandler.sendMessageDelayed(msg, ANIMATION_DURATION);
        mAnimationImg.setVisibility(View.VISIBLE);
    }

    public void loadWaitAnimation(){
        android.os.Message msg = webSocketHandler.obtainMessage(MSG_GREEN_ANIMATE);
        webSocketHandler.sendMessageDelayed(msg, ANIMATION_DURATION);

        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                mAnimationImg.setVisibility(View.VISIBLE);
            }
        });

    }

    public void stopSpeakAnimation(){
        webSocketHandler.removeMessages(MSG_GREEN_ANIMATE);
        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                mAnimationImg.setVisibility(View.GONE);
            }
        });

    }

    public void stopWaitAnimation(){
        webSocketHandler.removeMessages(MSG_RED_ANIMATE);

        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                mAnimationImg.setVisibility(View.GONE);
            }
        });
    }

    private void stopSpeak(){
        AudioManager.getInstance().stopRecord();
        AudioManager.getInstance().sendAudioFile(mCurrentChannelId, isUrgency, audioCallback);
        stopSpeakAnimation();
        updateTipStatusText(MIC_FINISH);
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//
//        AudioManager.getInstance().release();
//    }

    private void finishMic() {
        APPLog.zxhLog(TAG + " finishMic");

        API.getInstance().getChannelApi().finishMic(TAG, mCurrentChannelId, new ApiCallback<MicResult>() {
            @Override
            public void handleResult(MicResult result, VolleyError error) {
                if (error != null){
                    ToastMaker.showToastShort(getResources().getString(R.string.request_error) + error.getMessage());
                }else if (result != null && result.status == HttpStatus.SC_OK){
                }
            }
        });

        isMeSpeak = false;
        updateTipStatusText(MIC_FINISH);
        isUrgencyStatus(false);
    }
}